package org.richin.reflection.util;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.management.ReflectionException;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richin.array.util.ArrayUtils;
import org.richin.collection.util.CollectionUtils;
import org.richin.date.util.DateFormatUtils;
import org.richin.date.util.DateUtils;
import org.richin.io.util.UtilException;
import org.richin.lang.util.StringUtils;
import org.richin.system.util.Assert;
import org.springframework.util.ReflectionUtils;

public class ReflectUtils {
	private static final Log log = LogFactory.getLog(ReflectUtils.class);
	private static Map<Class<?>,Class<?>> primitiveTypesMap = new HashMap<Class<?>,Class<?>>();
	 protected static final String[] PRIMITIVE_NAMES = new String[] { "boolean",
         "byte", "char", "double", "float", "int", "long", "short", "void" };

 protected static final Class[] PRIMITIVES = new Class[] { boolean.class,
         byte.class, char.class, double.class, float.class, int.class,
         long.class, short.class, Void.TYPE };

	static {
		primitiveTypesMap.put(byte.class, Byte.class);
		primitiveTypesMap.put(boolean.class, Boolean.class);
		primitiveTypesMap.put(char.class, Character.class);
		primitiveTypesMap.put(double.class, Double.class);
		primitiveTypesMap.put(float.class, Float.class);
		primitiveTypesMap.put(int.class, Integer.class);
		primitiveTypesMap.put(long.class, Long.class);
		primitiveTypesMap.put(short.class, Short.class);
	}
	 /**
     * 强制转换fileld可访问.
     */
	public static void makeAccessible(final Field field) {
        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
                field.setAccessible(true);
        }
}
	 /**
     * 提取集合中的对象的属性(通过getter函数),组合成List.
     *
     * @param collection - 来源集合.
     * @param propertityName - 要提取的属性名.
     */
    @SuppressWarnings("unchecked")
    public static List fetchElementPropertyToList(final Collection collection,
                    final String propertyName) {
            List list = new ArrayList();

            try {
                    for (Object obj : collection) {
                            list.add(PropertyUtils.getProperty(obj, propertyName));
                    }
            } catch (Exception e) {
                    handleReflectionException(e);
            }

            return list;
    }
	@SuppressWarnings("unchecked")
	public static Class autoboxType(Class type) {
		final Class res = (Class) primitiveTypesMap.get(type);
		return res == null ? type : res;
	}

	public static boolean isArray(Class<?> klazz) {
		return klazz.getName().charAt(0) == '[';
	}
	 public static Class forName(String name) throws ClassNotFoundException {
	        if (null == name || "".equals(name)) {
	            return null;
	        }
	        Class c = forNamePrimitive(name);
	        if (c == null) {
	            if (name.endsWith("[]")) {
	                String nc = name.substring(0, name.length() - 2);
	                c = Class.forName(nc, true, Thread.currentThread().getContextClassLoader());
	                c = Array.newInstance(c, 0).getClass();
	            } else {
	                c = Class.forName(name, true, Thread.currentThread().getContextClassLoader());
	            }
	        }
	        return c;
	    }

	    protected static Class forNamePrimitive(String name) {
	        if (name.length() <= 8) {
	            int p = Arrays.binarySearch(PRIMITIVE_NAMES, name);
	            if (p >= 0) {
	                return PRIMITIVES[p];
	            }
	        }
	        return null;
	    }
	 /**
     * Converts an array of Class names to Class types
     * @param s
     * @return
     * @throws ClassNotFoundException
     */
    public static Class[] toTypeArray(String[] s) throws ClassNotFoundException {
        if (s == null)
            return null;
        Class[] c = new Class[s.length];
        for (int i = 0; i < s.length; i++) {
            c[i] = forName(s[i]);
        }
        return c;
    }
    /**
     * Converts an array of Class types to Class names
     * @param c
     * @return
     */
    public static String[] toTypeNameArray(Class[] c) {
        if (c == null)
            return null;
        String[] s = new String[c.length];
        for (int i = 0; i < c.length; i++) {
            s[i] = c[i].getName();
        }
        return s;
    }
	public static boolean isAssignableFrom(Class klazz, Class aClass) {
		if (klazz == aClass)
			return true;

		//	        SoftDoubleKeyMap.Entry val = (SoftDoubleKeyMap.Entry) assignableMap.getOrPut(klazz, aClass, null);
		//	        if (val.getValue() == null) {
		//	            val.setValue(Boolean.valueOf(klazz.isAssignableFrom(aClass)));
		//	        }
		//	        return ((Boolean)val.getValue()).booleanValue();
		return klazz.isAssignableFrom(aClass);
	}

	/**   
	 * 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
	 * @param obj 原始对象
	 * @return 新对象
	 * @throws NoSuchMethodException    
	 * @throws InvocationTargetException    
	 * @throws IllegalAccessException    
	 * @throws InstantiationException    
	 * @throws SecurityException    
	 * @throws IllegalArgumentException    
	 */
	@SuppressWarnings("unchecked")
	public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException,
			IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		//获得对象的类型    
		Class classType = obj.getClass();

		//通过默认构造方法去创建一个新的对象，getConstructor的视其参数决定调用哪个构造方法    
		Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});

		//获得对象的所有属性    
		Field[] fields = classType.getDeclaredFields();

		for (int i = 0; i < fields.length; i++) {
			//获取数组中对应的属性    
			Field field = fields[i];

			String fieldName = field.getName();
			String stringLetter = fieldName.substring(0, 1).toUpperCase();

			//获得相应属性的getXXX和setXXX方法名称    
			String getName = "get" + stringLetter + fieldName.substring(1);
			String setName = "set" + stringLetter + fieldName.substring(1);

			//获取相应的方法    
			Method getMethod = classType.getMethod(getName, new Class[] {});
			Method setMethod = classType.getMethod(setName, new Class[] { field.getType() });

			//调用源对象的getXXX（）方法    
			Object value = getMethod.invoke(obj, new Object[] {});

			//调用拷贝对象的setXXX（）方法    
			setMethod.invoke(objectCopy, new Object[] { value });
		}

		return objectCopy;
	}

	/**
	* 通过反射,获得定义Class时声明的父类的泛型参数的类型. 如public MyDao extends GenericHibernateDAO<My>
	* 返回My
	* @param clazz 继承泛型的对象
	* @return 返回继承泛型时声明的父类的泛型参数的类型, 如果没有声明则返回 <code>Object.class</code>
	*/
	@SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(Class clazz) {
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */
	public static Class getSuperClassGenricType(Class clazz, int index) {

		Type genType = clazz.getGenericSuperclass();

		if (!(genType instanceof ParameterizedType)) {
			log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0) {
			log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
					+ params.length);
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
			return Object.class;
		}
		return (Class) params[index];
	}

	@SuppressWarnings("unchecked")
	public static Field getField(Class clazz, String name) throws NoSuchFieldException {
		Field field = _getField(clazz, name);
		return field;
	}
	  /**
     * 暴力设置对象变量值，忽略private、protected修饰符的限制。
     *
     * @param object 对象
     * @param propertyName 属性名称
     * @param newValue 属性值
     * @throws NoSuchFieldException 没有该字段时抛出
     */
    public static void forceSetProperty(Object object, String propertyName, Object newValue)
                    throws NoSuchFieldException {
            Assert.notNull(object);
            Assert.hasText(propertyName);

            Field field = getDeclaredField(object, propertyName);
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            try {
                    field.set(object, newValue);
            } catch (IllegalAccessException e) {
                    log.info("Can't set " + object.getClass().getName() + "." + propertyName + "");
            }
            field.setAccessible(accessible);
    }
	/**
	 * 获取当前类声明的private/protected字段内容，而不必要求该字段上定义了getter方法
	 *
	 * @param object
	 *            要访问的对象
	 * @param propertyName
	 *            要访问的属性名
	 * @return 该属性的值
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 *
	 * <pre>
	 * //有一个对象book，我们不必知道它的具体类型，就可以用这个方法取出它私有的name字段内容
	 * BeanUtils.getPrivateProperty(book, &quot;name&quot;);
	 * </pre>
	 */
    public static Object getPrivateProperty(Object object, String propertyName)
                    throws IllegalAccessException, NoSuchFieldException {
            Assert.notNull(object);
            Assert.hasText(propertyName);
            Field field = object.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            return field.get(object);
    }

	/**
	 * 设置当前类声明的private/protected变量
	 *
	 * @param object
	 *            要访问的对象
	 * @param propertyName
	 *            要设置的属性名
	 * @param newValue
	 *            要设置的属性值
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 *
	 * <pre>
	 *    //有一个对象object，我们不必知道它的具体类型，就可以用这个方法设置它私有的name字段的值
	 *    BeanUtils.getPrivateProperty(object,&quot;name“,&quot;newvalue&quot;);
	 * </pre>
	 */
    public static void setPrivateProperty(Object object, String propertyName,
                    Object newValue) throws IllegalAccessException,
                    NoSuchFieldException {
            Assert.notNull(object);
            Assert.hasText(propertyName);

            Field field = object.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(object, newValue);
    }

	@SuppressWarnings("unchecked")
	private static final Field _getField(final Class clazz, final String name) throws NoSuchFieldException {
		Class cls = clazz;
		try {
			Field field = cls.getDeclaredField(name);
			return field;
		} catch (NoSuchFieldException e) {
			cls = cls.getSuperclass();
			if (null == cls) {
				throw e;
			}
			return _getField(cls, name);
		}
	}
	 /**
     * 获取对象的所有属性值
     *
     * @param object 对象实例
     * @return 属性集合
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Map<String, Object> getObjectAllProperties(Object object) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
            Map<String, Object> map = new HashMap<String, Object>();
            if (object != null) {
                    Method[] methods = object.getClass().getMethods();
                    for (int i = 0, n = methods.length; i < n; i ++) {
                            Method method = methods[i];
                            if ((method.getModifiers() & Modifier.PUBLIC) == 1
                                            && method.getDeclaringClass() != Object.class
                                            && (method.getParameterTypes() == null || method
                                                            .getParameterTypes().length == 0)) {
                                    String property = method.getName();
                                    if (property.startsWith("get")) {
                                            property = property.substring(3);
                                            String lower = property.substring(0, 1).toLowerCase() + property.substring(1);
                                            map.put(lower, method.invoke(object, new Object[0]));
                                    } else if (property.startsWith("is")) {
                                            property = property.substring(2);
                                            String lower = property.substring(0, 1).toLowerCase() + property.substring(1);
                                            map.put(lower, method.invoke(object, new Object[0]));
                                    }
                            }
                    }
            }
            return map;
    }
	/**
	 * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
	 */
	public static Object getFieldValueNotGetter(Object object, String fieldName) throws NoSuchFieldException {
		Field field = getDeclaredField(object, fieldName);
		if (!field.isAccessible()) {
			field.setAccessible(true);
		}

		Object result = null;
		try {
			result = field.get(object);
		} catch (IllegalAccessException e) {
			log.error("不可能抛出的异常{}" + e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 循环向上转型,获取对象的DeclaredField.
	 */
	public static Field getDeclaredField(Object object, String fieldName) throws NoSuchFieldException {
		Assert.notNull(object);
		return getDeclaredField(object.getClass(), fieldName);
	}

	/**
	 * 循环向上转型,获取类的DeclaredField.
	 */
	@SuppressWarnings("unchecked")
	public static Field getDeclaredField(Class clazz, String fieldName) throws NoSuchFieldException {
		Assert.notNull(clazz);
		Assert.hasText(fieldName);
		for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
			try {
				return superClass.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
				// Field不在当前类定义,继续向上转型
			}
		}
		throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + fieldName);
	}

    /**
     * 暴力调用对象函数,忽略private,protected修饰符的限制.
     *
     * @throws NoSuchMethodException 如果没有该Method时抛出.
     */
    public static Object invokePrivateMethod(Object object, String methodName, Object... params)
                    throws NoSuchMethodException {
            Assert.notNull(object);
            Assert.hasText(methodName);
            Class[] types = new Class[params.length];
            for (int i = 0; i < params.length; i++) {
                    types[i] = params[i].getClass();
            }

            Class clazz = object.getClass();
            Method method = null;
            for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
                    try {
                            method = superClass.getDeclaredMethod(methodName, types);
                            break;
                    } catch (NoSuchMethodException e) {
                            // 方法不在当前类定义,继续向上转型
                    }
            }

            if (method == null)
                    throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

            boolean accessible = method.isAccessible();
            method.setAccessible(true);
            Object result = null;
            try {
                    result = method.invoke(object, params);
            } catch (Exception e) {
                    handleReflectionException(e);
            }
            method.setAccessible(accessible);
            return result;
    }
	/**
	 * 调用当前类声明的private/protected函数
	 *
	 * @param object
	 *            要访问的对象
	 * @param methodName
	 *            要调用的方法名
	 * @param params
	 *            调用时传递的参数
	 * @return 调用后的返回值
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 *
	 * <pre>
	 * //有一个对象object，我们不必知道它的具体类型，就可以用这个方法调用它私有的disaccount方法，
	 * BeanUtils.getPrivateProperty(object, &quot;disaccount&quot;, 0.05);
	 * </pre>
	 */
	public static Object invokePrivateMethod1(Object object, String methodName, Object... params)
			throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		Assert.notNull(object);
		Assert.hasText(methodName);
		Class[] types = new Class[params.length];
		for (int i = 0; i < params.length; i++) {
			types[i] = params[i].getClass();
		}
		Method method = object.getClass().getDeclaredMethod(methodName, types);
		method.setAccessible(true);
		return method.invoke(object, params);
	}
    /**
     * 按Filed的类型取得Field列表.
     */
    public static List<Field> getFieldsByType(Object object, Class type) {
            List<Field> list = new ArrayList<Field>();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                    if (field.getType().isAssignableFrom(type)) {
                            list.add(field);
                    }
            }
            return list;
    }

    /**
     * 按FiledName获得Field的类型.
     */
    public static Class getPropertyType(Class type, String name) throws NoSuchFieldException {
            return getDeclaredField(type, name).getType();
    }

    /**
     * 获得field的getter函数名称.
     */
    public static String getGetterName(Class type, String fieldName) {
            Assert.notNull(type, "Type required");
            Assert.hasText(fieldName, "FieldName required");

            if (type.getName().equals("boolean")) {
                    return "is" + StringUtils.capitalize(fieldName);
            } else {
                    return "get" + StringUtils.capitalize(fieldName);
            }
    }

    /**
     * 获得field的getter函数,如果找不到该方法,返回null.
     */
    public static Method getGetterMethod(Class type, String fieldName) {
            try {
                    return type.getMethod(getGetterName(type, fieldName));
            } catch (NoSuchMethodException e) {
                    log.error(e.getMessage(), e);
            }
            return null;
    }
    /**
     * Determine whether the given method is a "toString" method.
     * @see java.lang.Object#toString()
     */
    public static boolean isToStringMethod(Method method) {
            return (method != null && method.getName().equals("toString") &&
                            method.getParameterTypes().length == 0);
    }

    /**
     * Determine whether the given method is an "equals" method.
     * @see java.lang.Object#equals
     */
    public static boolean isEqualsMethod(Method method) {
            if (method == null || !method.getName().equals("equals")) {
                    return false;
            }
            Class[] paramTypes = method.getParameterTypes();
            return (paramTypes.length == 1 && paramTypes[0] == Object.class);
    }
   
   
    /**
     * Determine whether the given method is a "hashCode" method.
     * @see java.lang.Object#hashCode
     */
    public static boolean isHashCodeMethod(Method method) {
            return (method != null && method.getName().equals("hashCode") &&
                            method.getParameterTypes().length == 0);
    }
    /**
     * Determine whether the given field is a "public static final" constant.
     * @param field the field to check
     */
    public static boolean isPublicStaticFinal(Field field) {
            int modifiers = field.getModifiers();
            return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
    }
    /**
     * Handle the given reflection exception. Should only be called if
     * no checked exception is expected to be thrown by the target method.
     * <p>Throws the underlying RuntimeException or Error in case of an
     * InvocationTargetException with such a root cause. Throws an
     * IllegalStateException with an appropriate message else.
     * @param ex the reflection exception to handle
     */
    public static void handleReflectionException(Exception ex) {
            if (ex instanceof NoSuchMethodException) {
                    throw new IllegalStateException("Method not found: " + ex.getMessage());
            }
            if (ex instanceof IllegalAccessException) {
                    throw new IllegalStateException("Could not access method: " + ex.getMessage());
            }
            if (ex instanceof InvocationTargetException) {
                    handleInvocationTargetException((InvocationTargetException) ex);
            }
            if (ex instanceof RuntimeException) {
                    throw (RuntimeException) ex;
            }
            handleUnexpectedException(ex);
    }
    /**
     * 将反射时的checked exception转换为unchecked exception。
     */
    public static void convertToUncheckedException(Exception e)
                    throws IllegalArgumentException {
            if (e instanceof IllegalAccessException
                            || e instanceof IllegalArgumentException
                            || e instanceof NoSuchMethodException)
                    throw new IllegalArgumentException("Refelction Exception.", e);
            else
                    throw new IllegalArgumentException(e);
    }
    /**
     * Handle the given invocation target exception. Should only be called if
     * no checked exception is expected to be thrown by the target method.
     * <p>Throws the underlying RuntimeException or Error in case of such
     * a root cause. Throws an IllegalStateException else.
     * @param ex the invocation target exception to handle
     */
    public static void handleInvocationTargetException(InvocationTargetException ex) {
            rethrowRuntimeException(ex.getTargetException());
    }

    /**
     * Rethrow the given {@link Throwable exception}, which is presumably the
     * <em>target exception</em> of an {@link InvocationTargetException}.
     * Should only be called if no checked exception is expected to be thrown by
     * the target method.
     * <p>Rethrows the underlying exception cast to an {@link RuntimeException}
     * or {@link Error} if appropriate; otherwise, throws an
     * {@link IllegalStateException}.
     * @param ex the exception to rethrow
     * @throws RuntimeException the rethrown exception
     */
    public static void rethrowRuntimeException(Throwable ex) {
            if (ex instanceof RuntimeException) {
                    throw (RuntimeException) ex;
            }
            if (ex instanceof Error) {
                    throw (Error) ex;
            }
            handleUnexpectedException(ex);
    }

    /**
     * Rethrow the given {@link Throwable exception}, which is presumably the
     * <em>target exception</em> of an {@link InvocationTargetException}.
     * Should only be called if no checked exception is expected to be thrown by
     * the target method.
     * <p>Rethrows the underlying exception cast to an {@link Exception} or
     * {@link Error} if appropriate; otherwise, throws an
     * {@link IllegalStateException}.
     * @param ex the exception to rethrow
     * @throws Exception the rethrown exception (in case of a checked exception)
     */
    public static void rethrowException(Throwable ex) throws Exception {
            if (ex instanceof Exception) {
                    throw (Exception) ex;
            }
            if (ex instanceof Error) {
                    throw (Error) ex;
            }
            handleUnexpectedException(ex);
    }

    /**
     * Throws an IllegalStateException with the given exception as root cause.
     * @param ex the unexpected exception
     */
    private static void handleUnexpectedException(Throwable ex) {
            // Needs to avoid the chained constructor for JDK 1.4 compatibility.
            IllegalStateException isex = new IllegalStateException("Unexpected exception thrown");
            isex.initCause(ex);
            throw isex;
    }

    /**
     * Determine whether the given method explicitly declares the given exception
     * or one of its superclasses, which means that an exception of that type
     * can be propagated as-is within a reflective invocation.
     * @param method the declaring method
     * @param exceptionType the exception to throw
     * @return <code>true</code> if the exception can be thrown as-is;
     * <code>false</code> if it needs to be wrapped
     */
    public static boolean declaresException(Method method, Class exceptionType) {
            Assert.notNull(method, "Method must not be null");
            Class[] declaredExceptions = method.getExceptionTypes();
            for (int i = 0; i < declaredExceptions.length; i++) {
                    Class declaredException = declaredExceptions[i];
                    if (declaredException.isAssignableFrom(exceptionType)) {
                            return true;
                    }
            }
            return false;
    }


	@SuppressWarnings("unchecked")
	public static Method getMethod(Class clazz, String methodName, Object[] args) throws NoSuchMethodException {
		Method mthd;
		if (args != null && args.length > 0) {
			// We need to get the argument type list so that we can differentiate override methods
			Class[] argTypes = new Class[args.length];
			for (int i = 0; i < args.length; i++) {
				if (args[i] != null) {
					// Check the primitive types first
					if (args[i] instanceof Boolean) {
						argTypes[i] = Boolean.TYPE;
					} else if (args[i] instanceof Character) {
						argTypes[i] = Character.TYPE;
					} else if (args[i] instanceof Byte) {
						argTypes[i] = Byte.TYPE;
					} else if (args[i] instanceof Short) {
						argTypes[i] = Short.TYPE;
					} else if (args[i] instanceof Integer) {
						argTypes[i] = Integer.TYPE;
					} else if (args[i] instanceof Long) {
						argTypes[i] = Long.TYPE;
					} else if (args[i] instanceof Float) {
						argTypes[i] = Float.TYPE;
					} else if (args[i] instanceof Double) {
						argTypes[i] = Double.TYPE;
					} else if (args[i] instanceof Void) {
						argTypes[i] = Void.TYPE;
					} else {
						argTypes[i] = args[i].getClass();
					}
				} else {
					argTypes[i] = Object.class;
				}
			}
			mthd = _getMethod(clazz, methodName, argTypes, null);
		} else {
			mthd = _getMethod(clazz, methodName, null, null);
		}
		return mthd;
	}

	@SuppressWarnings("unchecked")
	private static final Method _getMethod(final Class clazz, final String name, final Class[] argTypes,
			NoSuchMethodException firstNsme) throws NoSuchMethodException {
		Class cls = clazz;
		try {
			return cls.getDeclaredMethod(name, argTypes);
		} catch (NoSuchMethodException e) {
			if (null == firstNsme) {
				firstNsme = e; //记住整个方法查找链中第一个 NoSuchMethodException, 以便此后可以抛出这个 NoSuchMethodException
			}
			cls = cls.getSuperclass();
			if (null == cls) {
				throw firstNsme; //这里抛出的是整个查找链中第一个 NoSuchMethodException, 便于对错误进行准确定位
			}
			return _getMethod(cls, name, argTypes, firstNsme);
		}
	}

	public static Object callMethod(Object obj, String methodName, Object[] args) {
		try {
			Method mthd;
			mthd = getMethod(obj.getClass(), methodName, args);
			mthd.setAccessible(true);
			return mthd.invoke(obj, args);
		} catch (NoSuchMethodException ex) {
			throw new RuntimeException(ex);
		} catch (IllegalAccessException ex) {
			throw new RuntimeException(ex);
		} catch (InvocationTargetException ex) {
			throw new RuntimeException(ex.getTargetException());
		}
	}

	public static Class classForName(String name) throws ClassNotFoundException {
		try {
			ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
			if (contextClassLoader != null) {
				return contextClassLoader.loadClass(name);
			} else {
				return Class.forName(name);
			}
		} catch (Exception e) {
			return Class.forName(name);
		}
	}

	/**
	 * Convience method that returns class given the class name
	 *
	 * @param   className The name of the class (ie Foo)
	 * @return  The Class object for the class if it is found
	 * @throws  ReflectionException If the class name is invalid
	 * @throws ClassNotFoundException 
	 */
	public static Class findClass(String className) throws ReflectionException, ClassNotFoundException {
		return findClass(className, null);
	}

	/**
	 * Convience method that returns class given the package name and className
	 *
	 * @param   className The name of the class (ie Foo)
	 * @param   packageName (Optional) The name of the package (ie com.xor.util)
	 * @return  The Class object for the class if it is found
	 * @throws  ReflectionException If the class name is invalid
	 */
	public static Class findClass(String className, String packageName) throws ClassNotFoundException {

		assert (className != null) : "className == null";

		Class klass = null;
		try {
			if (StringUtils.isNotBlank(packageName)) {
				klass = Class.forName(className);
			} else {
				klass = Class.forName(packageName + "." + className);
			}
		} catch (ClassNotFoundException cnfe) {
			throw new ClassNotFoundException("Class not found: " + cnfe.getMessage(), cnfe);
		}

		return klass;
	}

	public static boolean isGetMethod(Method method) {
		return (method.getName().startsWith("get") && !method.getName().equals("get") || method.getName().startsWith(
				"is")
				&& !method.getName().equals("is"))
				&& method.getReturnType() != Void.TYPE && method.getParameterTypes().length == 0;
	}

	public static boolean isSetMethod(Method method) {
		return method.getName().startsWith("set") && !method.getName().equals("set")
				&& method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 1;
	}

	/**
	 *  Method works only for String values
	 */
	public static Object getObjectFromList(String fieldName, String value, List objList) {
		if (objList == null || objList.size() == 0 || fieldName == null || fieldName.length() == 0) {
			return null;
		}
		int count = objList.size();
		String requestedMethod = "get" + fieldName;
		Object obj = null;
		Class myClass = null;
		Method[] methods = null;
		Method method = null;
		String methodName = null;
		int methodCount = 0;
		Object methodValue = null;

		try {
			for (int i = 0; i < count; i++) {
				obj = (Object) objList.get(i);
				//                log.debug("##### obj = " + obj );
				//                log.debug("##### obj = " + getToString( obj ) );
				myClass = obj.getClass();
				methods = myClass.getDeclaredMethods();
				methodCount = methods.length;
				//                log.debug("##### methodCount = " + methodCount );
				for (int j = 0; j < methodCount; j++) {
					method = methods[j];
					methodName = method.getName();
					//                    log.debug( "==> methodName=" + methodName );
					// use only 'getter' methods with no parameters
					if (methodName.equalsIgnoreCase(requestedMethod) && method.getParameterTypes().length == 0) {
						//                                      log.debug( "==> methodName=" + methodName );
						//                        log.debug( "==> method=" + method );
						methodValue = method.invoke(obj, null);
						//                        log.debug( "==> methodValue=" + String.valueOf( methodValue ) );
						if (value.equalsIgnoreCase(String.valueOf(methodValue))) {
							return obj;
						}
					}// if

				}

			}
		} catch (Exception e) {
			log.debug("ERROR :: Exception thrown:\n" + e + " :: cause ::  " + e.getMessage());
		}// try-catch
		// return null ... since object now
		return null;
	}// getObjectFromList()

	/**
	 * 取得指定对象中某个字段的值。<BR>
	 *
	 * Get the value of the specified field.<BR>
	 *
	 * @param r_Object
	 * @param r_FieldName
	 * @return
	 */
	public static Object getFieldValue(Object r_Object, String r_FieldName) {

		Field t_Field;
		try {
			if (null == r_Object) {
				return null;
			}

			t_Field = r_Object.getClass().getDeclaredField(r_FieldName);

			if (null == t_Field) {
				t_Field = r_Object.getClass().getField(r_FieldName);
			}

			if (null != t_Field) {
				t_Field.setAccessible(true);
				return t_Field.get(r_Object);
			} else {
				return null;
			}

		} catch (Exception e) {
			if (e instanceof NoSuchFieldException) {
				try {
					//如果不存在 Field, 将查找所有父类的 Field, 依然不存在, 将 throw 异常
					return getNotAccessibleFieldValue(r_Object, r_FieldName);
				} catch (Exception ex1) {
					e.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
			// Nothing to do
		}

		return null;

	}

	private static Object getNotAccessibleFieldValue(Object r_Object, String r_FieldName)
			throws IllegalArgumentException, IllegalAccessException {
		Field t_Field = null;
		Class superClass = null;
		while (true) {
			superClass = r_Object.getClass().getSuperclass();
			if (superClass == null) {
				return null;
			}
			try {
				t_Field = superClass.getDeclaredField(r_FieldName);
				break;
			} catch (NoSuchFieldException noSuchFieldException1) {
				superClass = superClass.getSuperclass();
			}
		}
		if (null != t_Field) {
			t_Field.setAccessible(true);
			return t_Field.get(r_Object);
		} else {
			return null;
		}
	}

	/**
	 * 获取Class的Public方法列表
	 * 
	 * @param r_Class
	 * @return
	 */
	public static Method[] getPublicMethod(Class r_Class) {
		Method[] t_Methods = r_Class.getMethods();
		List t_ResultList = new ArrayList();
		for (int i = 0; i < t_Methods.length; i++) {
			int t_Modifiers = t_Methods[i].getModifiers();
			if (!Modifier.isPublic(t_Modifiers))
				continue;
			t_ResultList.add(t_Methods[i]);
		}
		return (Method[]) t_ResultList.toArray(new Method[t_ResultList.size()]);
	}

	/**
	 * 获取Method的方法签名
	 * 
	 * @param r_Method
	 * @return
	 */
	public static String getMethodSingnature(Method r_Method) {
		StringBuffer t_Buffer = new StringBuffer();
		String t_MethodName = r_Method.getName();
		t_Buffer.append(t_MethodName);
		t_Buffer.append("(");
		Class[] t_ParameterTypes = r_Method.getParameterTypes();
		for (int i = 0; i < t_ParameterTypes.length; i++) {
			t_Buffer.append(t_ParameterTypes[i].getSimpleName());
			if (i < (t_ParameterTypes.length - 1)) {
				t_Buffer.append(", ");
			}
		}
		t_Buffer.append(")");
		return t_Buffer.toString();
	}

	/**
	 * 根据类名得到该类所有的pulbic成员方法的方法名。
	 * 
	 * @param className 类名
	 * @return 所有的pulbic成员方法的方法名数组
	 * @since  0.4
	 */
	public static String[] getMethods(String className) {
		String methodNames[];
		try {
			Class c = Class.forName(className);
			Method methods[] = c.getMethods();
			methodNames = new String[methods.length];
			for (int i = 0; i < methods.length; i++) {
				methodNames[i] = methods[i].toString();
			}
			return methodNames;
		}

		catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据类名得到该类所申明的方法的方法名。
	 * 
	 * @param className 类名
	 * @return 所申明的方法的方法名数组
	 * @since  0.4
	 */
	public static String[] getDeclaredMethods(String className) {
		String methodNames[];
		try {
			Class c = Class.forName(className);
			Method methods[] = c.getDeclaredMethods();
			methodNames = new String[methods.length];
			for (int i = 0; i < methods.length; i++) {
				methodNames[i] = methods[i].toString();
			}
			return methodNames;
		}

		catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	* 通过方法名调用对象方法
	*
	* @param obj        类实例
	* @param methodName 方法名字
	* @param argsType   参数类型类表
	* @param args       参数列表
	* @return Object
	* @throws java.lang.Exception
	*/
	public static Object invoke(Object obj, String methodName, Class[] argsType, Object[] args) throws Exception {
		Method methodObj = null;
		Object valObj = null;
		methodObj = obj.getClass().getMethod(methodName, argsType);
		valObj = methodObj.invoke(obj, args);
		methodObj = null;
		methodName = null;
		argsType = null;
		args = null;
		return valObj;
	}

	/**
	 * 通过方法名调用对象方法
	 *
	 * @param obj        类实例
	 * @param methodName 方法名字
	 * @param args       参数对象列表
	 * @return
	 * @throws java.lang.Exception
	 */
	public static Object invoke(Object obj, String methodName, Object[] args) throws Exception {
		Class[] argsType = new Class[args.length];
		for (int i = 0; i < args.length; i++) {
			argsType[i] = args[i].getClass();
		}
		return invoke(obj, methodName, argsType, args);
	}

	/**
	 * 通过方法名调用类方法
	 *
	 * @param cls        类
	 * @param methodName 方法名字
	 * @param argsType   参数类型类表
	 * @param args       参数列表
	 * @return Object
	 * @throws java.lang.Exception
	 */
	public static Object invoke(Class cls, String methodName, Class[] argsType, Object[] args) throws Exception {
		Object invokeObj = cls.newInstance();
		return invoke(invokeObj, methodName, argsType, args);
	}

	/**
	 * 通过方法名调用对象无参数方法
	 *
	 * @param invokeObj
	 * @param methodName
	 * @return
	 * @throws java.lang.Exception
	 */
	public static Object invoke(Object invokeObj, String methodName) throws Exception {
		return invoke(invokeObj, methodName, null, null);
	}

	/**
	 * 指定构造参数类型和参数构造类实例
	 *
	 * @param cls
	 * @param argsType
	 * @param args
	 * @return
	 * @throws java.lang.Exception
	 */
	public static Object getInstance(Class cls, Class[] argsType, Object[] args) throws Exception {
		Object obj = null;
		Constructor constructor = cls.getConstructor(argsType);
		obj = constructor.newInstance(args);
		return obj;
	}

	/**
	 * 检查一个类是否实现了指定的接口
	 *
	 * @param classClass     类
	 * @param interfaceClass 接口类
	 * @return
	 */
	public static boolean isImplements(Class classClass, Class interfaceClass) {
		Class[] interfaceClassL = classClass.getInterfaces();
		for (int i = 0; interfaceClassL != null && i < interfaceClassL.length; i++) {
			if (interfaceClass.equals(interfaceClassL[i]))
				return true;
		}
		return false;
	}

	public static Method findMethodByName(Class clazz, String methodName) {
		int count = 0;
		Method actionMethod = null;
		Method[] methods = clazz.getMethods();
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].getName().equals(methodName)) {
				count++;
				if (count > 1) {
					throw new RuntimeException(clazz + " 类中有重载的同名方法: " + methodName + ",无法判定使用哪一个！");
				}
				actionMethod = methods[i];
			}
		}
		if (count == 0 || actionMethod == null) {
			throw new RuntimeException(clazz + " 类中找到不方法: " + methodName);
		}
		return actionMethod;
	}

	public static String getLowerClassName(Class clazz) {
		String className = clazz.getName();
		int index = className.lastIndexOf(".");
		if (index != -1) {
			className = className.substring(index + 1);
		}
		return className.substring(0, 1).toLowerCase() + className.substring(1);
	}

	/**
	 *
	 * 方法描述 得到一个类指定类型的所有属性.
	 *
	 * @param clazz
	 * @param type
	 * @return Object[]
	 */
	public static List findFieldsByType(Class clazz, String type) {
		if (clazz == null)
			return null;
		List list = new ArrayList();
		Field[] fa = clazz.getDeclaredFields();
		for (int j = 0; j < fa.length; j++) {
			Class cl = fa[j].getType();
			String fieldName = fa[j].getName();
			if (StringUtils.isNotNullStr(type)) {
				if (type.equals(cl.getName())) {
					list.add(fieldName);
				}
			} else {
				list.add(fieldName);
			}
		}
		return list;
	}

	/**
	     *
	     * 方法描述 得到一个类指定类型的所有属性.
	     *List<String> filedList=findFieldsByType(StringUtils.class,new String[]{"String","void","int","char","byte","boolean","long"});
	     * @param clazz
	     * @param type[]
	     * @return Object[]
	     */
	public static List<String> findFieldsByType(Class<?> clazz, String[] type) {
		if (clazz == null)
			return null;
		List<String> list = new ArrayList<String>();
		Field[] fa = clazz.getDeclaredFields();
		for (int j = 0; j < fa.length; j++) {
			Class<?> cl = fa[j].getType();
			String fieldName = fa[j].getName();
			if (type != null && type.length > 0) {
				if (ArrayUtils.contains(type, cl.getName())) {
					list.add(fieldName);
				}
			} else {
				list.add(fieldName);
			}
		}
		return list;
	}

	/**
	 * 设置POJO对象的属性值
	 *
	 * @param object
	 * @param methodName
	 * @param value
	 * @exception Exception
	 */
	public static void setMethodValue(Object object, String methodName, Object value) throws Exception {
		Method method = getMethod(object, methodName);
		method.invoke(object, new Object[] { value });
	}

	/**
	 * 设置POJO对象的属性值
	 *
	 * @param object
	 * @param prefix
	 * @param fieldName
	 * @param value
	 * @throws Exception
	 */
	public static void setMethodValue(Object object, String prefix, String fieldName, Object value) throws Exception {
		setMethodValue(object, getMethodName(prefix, fieldName), value);
	}

	/**
	 * 获得Bean属性的方法名
	 *
	 * @param perfix
	 * @param fieldName
	 * @return String
	 */
	public static String getMethodName(String prefix, String fieldName) {
		StringBuffer methodName = new StringBuffer();
		methodName.append(prefix.trim());
		methodName.append(fieldName.trim().substring(0, 1).toUpperCase());
		methodName.append(fieldName.trim().substring(1));
		return methodName.toString();
	}

	/**
	 * 获得POJO对象中的属性值
	 *
	 * @param object
	 * @param methodName
	 * @return Object
	 * @exception Exception
	 */
	public static Object getMethodValue(Object object, String methodName) throws Exception {
		Method method = getMethod(object, methodName);
		return method.invoke(object, new Object[] {});
	}

	/**
	 * 获得POJO对象中的属性值
	 *
	 * @param object
	 * @param prefix
	 * @param fieldName
	 * @return Object
	 * @throws Exception
	 */
	public static Object getMethodValue(Object object, String prefix, String fieldName) throws Exception {
		return getMethodValue(object, getMethodName(prefix, fieldName));
	}

	/**
	 * 通过方法名获得对象中的方法
	 *
	 * @param obj
	 * @param methodName
	 * @return Method
	 */
	public static Method getMethod(Object obj, String methodName) throws Exception {
		Method[] methods = obj.getClass().getDeclaredMethods();
		int length = methods.length;
		for (int i = 0; i < length; i++) {
			String name = methods[i].getName().trim();
			methodName = methodName.trim();
			if (name.equals(methodName)) {
				return methods[i];
			}
		}
		return null;
	}

	/**
	 * 通过指定的前缀和属性名称来获得对象中的特殊方法.
	 *
	 * @param obj
	 * @param prefix
	 * @param propertyName
	 * @return Method
	 * @exception Exception
	 */
	public static Method getMethod(Object obj, String prefix, String fieldName) throws Exception {
		String methodName = getMethodName(prefix, fieldName);
		return getMethod(obj, methodName);
	}

	/**
	 * 获得对象中的所有方法
	 *
	 * @param object
	 * @return Method[]
	 */
	public static Method[] getMethods(Object object) {
		return object.getClass().getDeclaredMethods();
	}

	/**
	 * 获得对象中的所有属性
	 *
	 * @param object
	 * @return Field[]
	 */
	public static Field[] getFeilds(Object object) {
		return object.getClass().getDeclaredFields();
	}

	/**
	 * 获得对象中的所有字段的名称
	 *
	 * @param object
	 * @return String[]
	 */
	public static String[] getFiledsName(Object object) {
		Field[] fields = getFeilds(object);
		int length = fields.length;
		String[] fieldsName = new String[length];
		for (int i = 0; i < length; i++) {
			fieldsName[i] = fields[i].getName();
		}
		return fieldsName;
	}

	/**
	 * 返回对象中的所有字段信息
	 *
	 * @param object
	 * @return Map
	 */
	public static Map<String, Object> getFeildsInfo(Object object) {
		Field[] fields = getFeilds(object);
		int length = fields.length;
		String[] fieldsName = new String[length];
		Class<?>[] fieldsType = new Class<?>[length];
		for (int i = 0; i < length; i++) {
			fieldsName[i] = fields[i].getName();
			fieldsType[i] = fields[i].getType();
		}
		Map<String, Object> fieldsMap = new HashMap<String, Object>(2);
		fieldsMap.put(FIELDS_NAME, fieldsName);
		fieldsMap.put(FIELDS_TYPE, fieldsType);
		return fieldsMap;
	}

	public static final String FIELDS_NAME = "fieldsName";
	public static final String FIELDS_TYPE = "fieldsType";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Class<?> c = StringUtils.class;
	    String s ="" ;
	   // System.out.println(c.g);
		//System.out.println(ArrayUtils.toString(map.get(FIELDS_NAME)));
	/*	List<String> filedList=findFieldsByType(StringUtils.class,new String[]{"String","void","int","char","byte","boolean","long"});
		for (Iterator<String> iterator = filedList.iterator(); iterator.hasNext();) {
			System.out.println(iterator.next());
			
		}*/
	}
	
    /**
     * 得到对象的公共属性
     * @param obj
     * @param fieldName
     * @return 该属性对象
     * @throws Exception
     */
    public static Object getPublicProperty(Object obj, String fieldName)throws UtilException {
    	try{
	        Class<? extends Object> cls = obj.getClass();
	        return  cls.getField(fieldName).get(obj);
    	}catch(Exception e){
			throw new UtilException(e);
		}
    }
    
    /**
     * 得到类的静态公共属性
     * @param className   类名
     * @param fieldName   属性名
     * @return 该属性对象
     * @throws UtilException
     */
    public static Object getStaticProperty(String className, String fieldName)throws UtilException  {
    	try{
	        Class<? extends Object> cls = Class.forName(className);
	        return cls.getField(fieldName).get(cls);
	    }catch(Exception e){
			throw new UtilException(e);
		}
    }

    /**
     * 执行某类的静态方法
     * @param className 类名
     * @param methodName 方法名
     * @param args 参数数组
     * @return 执行方法返回的结果
     * @throws Exception
     */
    public static Object invokeStaticMethod(Class<?> cls, String methodName,Object...params) throws UtilException {
    	try{
	        if(params==null)return cls.getMethod(methodName,new Class[]{}).invoke(null);
	        Class<?>[] argsClass = new Class[params.length];
	        for (int i = 0; i < params.length; i++) {
	            argsClass[i] = params[i].getClass();
	        }
	        return cls.getMethod(methodName, argsClass).invoke(null,params);
    	}catch(Exception e){
			throw new UtilException(e);
		}
    }

    /**
     * 新建实例
     * @param className 类名
     * @param args 构造函数的参数
     * @return 新建的实例
     * @throws Exception
     */
    public static Object newInstance(Class<?> cls, Object...params)throws UtilException{
    	try{
	        if(params==null)return cls.getConstructor(new Class[]{}).newInstance();
	        Class<?>[] argsClass = new Class[params.length];
	        for (int i = 0, j = params.length; i < j; i++) {
	            argsClass[i] = params[i].getClass();
	        }
	        return cls.getConstructor(argsClass).newInstance(params);
	    }catch(Exception e){
			throw new UtilException(e);
		}
    }


    
    /**
     * 判断是否是某个类的实例
     * @param obj 实例
     * @param cls 类
     * @return 如果 obj 是此类的实例,则返回 true
     */
    public static boolean isInstance(Object obj, Class<? extends Object> cls) {
        return cls.isInstance(obj);
    }
    
    /**
     * 得到数组中的某个元素
     * @param array 数组
     * @param index 索引
     * @return 返回指定数组对象中索引组件的值
     */
    public static Object getByArray(Object array, int index) {
        return Array.get(array,index);
    }
    
	/**
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with
	 * the supplied <code>name</code>. Searches all superclasses up to {@link Object}.
	 * @param clazz the class to introspect
	 * @param name the name of the field
	 * @return the corresponding Field object, or <code>null</code> if not found
	 */
	public static Field findField(Class<?> clazz, String name) {
		return findField(clazz, name, null);
	}

	/**
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with
	 * the supplied <code>name</code> and/or {@link Class type}. Searches all
	 * superclasses up to {@link Object}.
	 * @param clazz the class to introspect
	 * @param name the name of the field (may be <code>null</code> if type is specified)
	 * @param type the type of the field (may be <code>null</code> if name is specified)
	 * @return the corresponding Field object, or <code>null</code> if not found
	 */
	public static Field findField(Class<?> clazz, String name, Class<?> type) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
		Class<?> searchType = clazz;
		while (!Object.class.equals(searchType) && searchType != null) {
			Field[] fields = searchType.getDeclaredFields();
			for (Field field : fields) {
				if ((name == null || name.equals(field.getName())) &&
						(type == null || type.equals(field.getType()))) {
					return field;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}

	/**
	 * Set the field represented by the supplied {@link Field field object} on
	 * the specified {@link Object target object} to the specified
	 * <code>value</code>. In accordance with
	 * {@link Field#set(Object, Object)} semantics, the new value is
	 * automatically unwrapped if the underlying field has a primitive type.
	 * <p>Thrown exceptions are handled via a call to
	 * {@link #handleReflectionException(Exception)}.
	 * @param field the field to set
	 * @param target the target object on which to set the field
	 * @param value the value to set; may be <code>null</code>
	 */
	public static void setField(Field field, Object target, Object value) {
		try {
			field.set(target, value);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
		}
	}

	/**
	 * Get the field represented by the supplied {@link Field field object} on
	 * the specified {@link Object target object}. In accordance with
	 * {@link Field#get(Object)} semantics, the returned value is
	 * automatically wrapped if the underlying field has a primitive type.
	 * <p>Thrown exceptions are handled via a call to
	 * {@link #handleReflectionException(Exception)}.
	 * @param field the field to get
	 * @param target the target object from which to get the field
	 * @return the field's current value
	 */
	public static Object getField(Field field, Object target) {
		try {
			return field.get(target);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
		}
	}

	/**
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
	 * and no parameters. Searches all superclasses up to <code>Object</code>.
	 * <p>Returns <code>null</code> if no {@link Method} can be found.
	 * @param clazz the class to introspect
	 * @param name the name of the method
	 * @return the Method object, or <code>null</code> if none found
	 */
	public static Method findMethod(Class<?> clazz, String name) {
		return findMethod(clazz, name, new Class[0]);
	}

	/**
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
	 * and parameter types. Searches all superclasses up to <code>Object</code>.
	 * <p>Returns <code>null</code> if no {@link Method} can be found.
	 * @param clazz the class to introspect
	 * @param name the name of the method
	 * @param paramTypes the parameter types of the method
	 * (may be <code>null</code> to indicate any signature)
	 * @return the Method object, or <code>null</code> if none found
	 */
	public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(name, "Method name must not be null");
		Class<?> searchType = clazz;
		while (searchType != null) {
			Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
			for (Method method : methods) {
				if (name.equals(method.getName()) &&
						(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
					return method;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}
	/**
	 * Invoke the specified {@link Method} against the supplied target object
	 * with no arguments. The target object can be <code>null</code> when
	 * invoking a static {@link Method}.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @return the invocation result, if any
	 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
	 */
	public static Object invokeMethod(Method method, Object target) {
		return invokeMethod(method, target, new Object[0]);
	}

	/**
	 * Invoke the specified {@link Method} against the supplied target object
	 * with the supplied arguments. The target object can be <code>null</code>
	 * when invoking a static {@link Method}.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @param args the invocation arguments (may be <code>null</code>)
	 * @return the invocation result, if any
	 */
	public static Object invokeMethod(Method method, Object target, Object... args) {
		try {
			return method.invoke(target, args);
		}
		catch (Exception ex) {
			handleReflectionException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}

	/**
	 * Invoke the specified JDBC API {@link Method} against the supplied
	 * target object with no arguments.
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @return the invocation result, if any
	 * @throws SQLException the JDBC API SQLException to rethrow (if any)
	 * @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[])
	 */
	public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
		return invokeJdbcMethod(method, target, new Object[0]);
	}

	/**
	 * Invoke the specified JDBC API {@link Method} against the supplied
	 * target object with the supplied arguments.
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @param args the invocation arguments (may be <code>null</code>)
	 * @return the invocation result, if any
	 * @throws SQLException the JDBC API SQLException to rethrow (if any)
	 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
	 */
	public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
		try {
			return method.invoke(target, args);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
		}
		catch (InvocationTargetException ex) {
			if (ex.getTargetException() instanceof SQLException) {
				throw (SQLException) ex.getTargetException();
			}
			handleInvocationTargetException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}


	/**
	 * Make the given method accessible, explicitly setting it accessible if necessary.
	 * The <code>setAccessible(true)</code> method is only called when actually necessary,
	 * to avoid unnecessary conflicts with a JVM SecurityManager (if active).
	 * @param method the method to make accessible
	 * @see java.lang.reflect.Method#setAccessible
	 */
	public static void makeAccessible(Method method) {
		if (!Modifier.isPublic(method.getModifiers()) ||
				!Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
			method.setAccessible(true);
		}
	}

	/**
	 * Make the given constructor accessible, explicitly setting it accessible if necessary.
	 * The <code>setAccessible(true)</code> method is only called when actually necessary,
	 * to avoid unnecessary conflicts with a JVM SecurityManager (if active).
	 * @param ctor the constructor to make accessible
	 * @see java.lang.reflect.Constructor#setAccessible
	 */
	public static void makeAccessible(Constructor<?> ctor) {
		if (!Modifier.isPublic(ctor.getModifiers()) ||
				!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
			ctor.setAccessible(true);
		}
	}


	/**
	 * Perform the given callback operation on all matching methods of the
	 * given class and superclasses.
	 * <p>The same named method occurring on subclass and superclass will
	 * appear twice, unless excluded by a {@link MethodFilter}.
	 * @param targetClass class to start looking at
	 * @param mc the callback to invoke for each method
	 * @see #doWithMethods(Class, MethodCallback, MethodFilter)
	 */
	public static void doWithMethods(Class<?> targetClass, MethodCallback mc) throws IllegalArgumentException {
		doWithMethods(targetClass, mc, null);
	}

	/**
	 * Perform the given callback operation on all matching methods of the
	 * given class and superclasses.
	 * <p>The same named method occurring on subclass and superclass will
	 * appear twice, unless excluded by the specified {@link MethodFilter}.
	 * @param targetClass class to start looking at
	 * @param mc the callback to invoke for each method
	 * @param mf the filter that determines the methods to apply the callback to
	 */
	public static void doWithMethods(Class<?> targetClass, MethodCallback mc, MethodFilter mf)
			throws IllegalArgumentException {

		// Keep backing up the inheritance hierarchy.
		do {
			Method[] methods = targetClass.getDeclaredMethods();
			for (Method method : methods) {
				if (mf != null && !mf.matches(method)) {
					continue;
				}
				try {
					mc.doWith(method);
				}
				catch (IllegalAccessException ex) {
					throw new IllegalStateException(
							"Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
				}
			}
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null);
	}

	/**
	 * Get all declared methods on the leaf class and all superclasses.
	 * Leaf class methods are included first.
	 */
	public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
		final List<Method> methods = new ArrayList<Method>(32);
		doWithMethods(leafClass, new MethodCallback() {
			public void doWith(Method method) {
				methods.add(method);
			}
		});
		return methods.toArray(new Method[methods.size()]);
	}


	/**
	 * Invoke the given callback on all fields in the target class,
	 * going up the class hierarchy to get all declared fields.
	 * @param targetClass the target class to analyze
	 * @param fc the callback to invoke for each field
	 */
	public static void doWithFields(Class<?> targetClass, FieldCallback fc) throws IllegalArgumentException {
		doWithFields(targetClass, fc, null);
	}

	/**
	 * Invoke the given callback on all fields in the target class,
	 * going up the class hierarchy to get all declared fields.
	 * @param targetClass the target class to analyze
	 * @param fc the callback to invoke for each field
	 * @param ff the filter that determines the fields to apply the callback to
	 */
	public static void doWithFields(Class<?> targetClass, FieldCallback fc, FieldFilter ff)
			throws IllegalArgumentException {

		// Keep backing up the inheritance hierarchy.
		do {
			// Copy each field declared on this class unless it's static or file.
			Field[] fields = targetClass.getDeclaredFields();
			for (Field field : fields) {
				// Skip static and final fields.
				if (ff != null && !ff.matches(field)) {
					continue;
				}
				try {
					fc.doWith(field);
				}
				catch (IllegalAccessException ex) {
					throw new IllegalStateException(
							"Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
				}
			}
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);
	}

	/**
	 * Given the source object and the destination, which must be the same class
	 * or a subclass, copy all fields, including inherited fields. Designed to
	 * work on objects with public no-arg constructors.
	 * @throws IllegalArgumentException if the arguments are incompatible
	 */
	public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
		if (src == null) {
			throw new IllegalArgumentException("Source for field copy cannot be null");
		}
		if (dest == null) {
			throw new IllegalArgumentException("Destination for field copy cannot be null");
		}
		if (!src.getClass().isAssignableFrom(dest.getClass())) {
			throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() +
					"] must be same or subclass as source class [" + src.getClass().getName() + "]");
		}
		doWithFields(src.getClass(), new FieldCallback() {
			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
				makeAccessible(field);
				Object srcValue = field.get(src);
				field.set(dest, srcValue);
			}
		}, COPYABLE_FIELDS);
	}


	/**
	 * Action to take on each method.
	 */
	public static interface MethodCallback {

		/**
		 * Perform an operation using the given method.
		 * @param method the method to operate on
		 */
		void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
	}


	/**
	 * Callback optionally used to method fields to be operated on by a method callback.
	 */
	public static interface MethodFilter {

		/**
		 * Determine whether the given method matches.
		 * @param method the method to check
		 */
		boolean matches(Method method);
	}


	/**
	 * Callback interface invoked on each field in the hierarchy.
	 */
	public static interface FieldCallback {

		/**
		 * Perform an operation using the given field.
		 * @param field the field to operate on
		 */
		void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
	}


	/**
	 * Callback optionally used to filter fields to be operated on by a field callback.
	 */
	public static interface FieldFilter {

		/**
		 * Determine whether the given field matches.
		 * @param field the field to check
		 */
		boolean matches(Field field);
	}
	/**
	 * Pre-built FieldFilter that matches all non-static, non-final fields.
	 */
	public static FieldFilter COPYABLE_FIELDS = new FieldFilter() {
		public boolean matches(Field field) {
			return !(Modifier.isStatic(field.getModifiers()) ||
					Modifier.isFinal(field.getModifiers()));
		}
	};

	/**
	 * 
	 * @param obj
	 * @param getterName
	 * @return
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static Object invokeGetMethod(Object obj,String getterName) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		return obj.getClass().getMethod(getterName).invoke(obj);
	}
	/**
     * Copy the values of all instance variable from a destination to a target
     * object, avoiding so to create a new instance of the target object.
     *
     * @param source
     * @param target
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    static public <T> void copyInto(T source, T target)
                    throws NoSuchFieldException, IllegalArgumentException,
                    IllegalAccessException {
            Field[] fields = getAllDeclaredFields(source);
            for (Field field : fields) {
                    field.setAccessible(true);
                    Object sourcevalue = field.get(source);
                    field.set(target, sourcevalue);
            }
    }
    /**
     * Inject a field in an object, also when in a superclass
     *
     * @param objectToBeInjected
     * @param objectToInject
     * @param fieldName
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    static public void injectField(Object objectToBeInjected,
                    Object objectToInject, String fieldName)
                    throws NoSuchFieldException, IllegalArgumentException,
                    IllegalAccessException {
            Field field = getDeclaredField(objectToBeInjected, fieldName);
            field.setAccessible(true);
            field.set(objectToBeInjected, objectToInject);
    }


    /**
     * Retrieve all fields, also when in a superclass
     *
     * @param object
     * @return the array of fields, included they that are in all superclasses
     * @throws NoSuchFieldException
     */
    static public Field[] getAllDeclaredFields(Object object)
                    throws NoSuchFieldException {
            Class<?> clazz = object.getClass();
            List<Field> fieldList = new ArrayList<Field>();

            collectAllDeclaredFields(clazz, Object.class, fieldList);

            return fieldList.toArray(new Field[fieldList.size()]);
    }

    /**
     * recursiv method
     */
    static private void collectAllDeclaredFields(Class<?> clazz,
                    Class<?> baseClass, List<Field> result) {
            if (clazz != baseClass) {
                    collectAllDeclaredFields(clazz.getSuperclass(), baseClass, result);

                    Field[] fields = clazz.getDeclaredFields();
                    for (int i = 0; i < fields.length; i++) {
                            result.add(fields[i]);
                    }
            }
    }

    /**
     * 执行某对象方法
     * @param owner 对象
     * @param methodName 方法名
     * @param args  参数
     * @return 方法返回值
     * @throws Exception
     */
    public static Object invokeMethod(Object obj, String methodName,Object...params)throws UtilException {
    	try{
	        Class<? extends Object> cls = obj.getClass();
	        if(params==null)return cls.getMethod(methodName,new Class[]{}).invoke(obj);
	        Class<?>[] argsClass = new Class[params.length];
	        for (int i = 0;i < params.length; i++) {
	            argsClass[i] = params[i].getClass();
	        }
	        return cls.getMethod(methodName, argsClass).invoke(obj,params);
	    }catch(Exception e){
			throw new UtilException(e);
		}
    }

}
